package com.yupi.springbootinit.messagecenter;

import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.mq.EventEnvelope;
import com.yupi.springbootinit.service.workflow.WorkflowTaskCreationService;
import com.yupi.springbootinit.service.workflow.WorkflowTaskUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 监听 PMC 版次发布事件，生成生产部任务（支持认领）
 * 路由键：pmc.batch.submitted
 * 负载字段：batchId, orderNumber, productName, departmentCode(部门编码), taskType, submittedBy, submittedByName
 */
@Component
@Slf4j
public class ProductionTaskListener {

    @Resource
    private WorkflowTaskCreationService workflowTaskCreationService;

    @Resource
    private WorkflowTaskUtils workflowTaskUtils;

    // @RabbitListener(queues = RabbitMqConfig.QUEUE_PMC_BATCH_SUBMITTED)  // RabbitMQ 已暂停使用
    public void onPmcBatchSubmitted(EventEnvelope env) {
        try {
            Object payloadObj = env.payload();
            if (!(payloadObj instanceof Map)) {
                log.warn("pmc.batch.submitted payload 非 Map，忽略。type={}, id={}", env.type(), env.eventId());
                return;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> payload = (Map<String, Object>) payloadObj;

            Long batchId = toLong(payload.get("batchId"));
            String orderNumber = toStr(payload.get("orderNumber"));
            String productName = toStr(payload.get("productName"));
            String departmentCode = toStr(payload.get("departmentCode")); // SC001
            String taskType = toStr(payload.get("taskType")); // PRODUCTION_PREP_CLEANING
            Long submittedBy = toLong(payload.get("submittedBy"));
            String submittedByName = toStr(payload.get("submittedByName"));

            if (batchId == null || departmentCode == null) {
                log.warn("缺少必要字段，batchId={}, departmentCode={}", batchId, departmentCode);
                return;
            }

            // 根据部门编码定位部门
            Department dept = workflowTaskUtils.getDepartmentByCode(departmentCode);
            if (dept == null) {
                log.error("找不到部门，departmentCode={}", departmentCode);
                return;
            }

            // 创建生产部任务（清机等），归属部门编码由服务内部常量控制（SC001）
            try {
                workflowTaskCreationService.createProductionPrepTaskForBatch(
                        batchId,
                        orderNumber,
                        productName,
                        taskType,
                        submittedBy,
                        submittedByName
                );
                log.info("已创建生产部任务: batchId={}, taskType={}, orderNumber={}, productName={}",
                        batchId, taskType, orderNumber, productName);
            } catch (Exception e) {
                log.error("创建生产部任务失败 batchId={}", batchId, e);
            }
        } catch (Exception e) {
            log.error("消费 pmc.batch.submitted 失败 type={}, id={}", env.type(), env.eventId(), e);
        }
    }

    private Long toLong(Object v) {
        if (v == null) return null;
        if (v instanceof Number) return ((Number) v).longValue();
        try { return Long.parseLong(v.toString()); } catch (Exception ignored) { return null; }
    }
    private String toStr(Object v) { return v == null ? null : v.toString(); }
}